/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.transas.zorlog.ui;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


/**
 *
 * @author amalikov
 */
public class FormatList {
	public FormatList(String path) {
		this.path = path;
		formats = new ArrayList<>();
	}
	
	public void read() {
		formats.clear();
		
		String[] fileNames = new File(path).list(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return name.toLowerCase().endsWith(".xml");
			}
		});
		
		for (String fileName : fileNames) {
			final Info info = readInfo(path + "/" + fileName);
			if (info != null)
				formats.add(info);
		}
	}
	
	public List<Info> getAll() {
		return formats;
	}
	
	public Info getByName(String name) {
		if (name != null) {
			for (Info info : formats) {
				if (name.equals(info.name))
					return info;
			}
		}
		return new Info("", "", "", "");
	}
	
	private Info readInfo(String fileName) {
		try (Reader file = new FileReader(fileName)) {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(file));
			NamedNodeMap infoAttrs = doc.getDocumentElement().getElementsByTagName("info").item(0).getAttributes();
			String name = infoAttrs.getNamedItem("name").getNodeValue();
			String ext = infoAttrs.getNamedItem("ext").getNodeValue();
			String type = infoAttrs.getNamedItem("type").getNodeValue();
			return new Info(fileName, name, ext, type);
        } catch (FileNotFoundException ex) {
			// do nothing
		} catch (SAXException | IOException | ParserConfigurationException ex) {
            Logger.getLogger(AppConfig.class.getName()).log(Level.SEVERE, null, ex);
        }
		
		return null;
	}
	
	public class Info {
		public Info(String fileName, String name, String ext, String type) {
			this.fileName = fileName;
			this.name = name;
			this.ext = ext.split(";");
			this.type = type;
		}
		
		final public String fileName;
		final public String name;
		final public String[] ext;
		final public String type;
	}
	
	private final String path;
	private List<Info> formats;
}
